import java.io.File

fun main() {
    val dpFileModifier = DpFileModifier()
    dpFileModifier.modifyFiles(File("/Users/jerry/projects/mine/gitee/demos/pluginDemo/modifyTextPluginDemo/123"))
}

class DpFileModifier {
    private val newLine = "\n"
    private val toProcessFileSuffix = ".xml"
    private val ignoreDirList = listOf(".git", ".gradle", ".idea", "gradle", "build")
    fun modifyFiles(file: File) {
        if (file.isDirectory && isDirToProcess(file.name)) {
            file.listFiles()?.forEach {
                modifyFiles(it)
            }
        } else {
            if (file.absolutePath.endsWith(toProcessFileSuffix)) {
                modifySingleFile(file)
            }
        }
    }

    private fun isDirToProcess(dirName: String): Boolean {
        var result = true
        ignoreDirList.forEach {
            if (it == dirName) {
                result = false
                return result
            }
        }
        return result
    }

    fun modifySingleFile(file: File) {
        var lineList = mutableListOf<String>()
        file.readLines().forEach {
            lineList.add(modify(it))
        }
        file.writeText(lineList.joinToString(separator = newLine))
    }

    private fun modify(line: String): String {
        var result = line
        val regex = Regex(".*=\"[0-9]*[s|d]p\".*")
        if (line.contains(regex)) {
            result = line.replace("=\"", "=\"@dimen/dp_")
                    .replace("dp\"", "\"")
                    .replace("sp\"", "\"")
        }
        return result
    }
}